package com.example.huichaoliu;

import org.apache.http.HttpRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.huichaoliu.data.UserInfo;
import com.rederxu.farmer.BaseActivity;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;
import com.rederxu.tools.Dialog;
import com.source.utils.Utils;

public class ReceiptAddressActivity extends BaseActivity implements OnClickListener,OnItemClickListener,OnItemLongClickListener {

	private ListView listView = null;
	private final int CODE_BACK_FROM_ADD = 100;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_receipt_address);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.left_button:
			finish();
			break;
		case R.id.btn_add:
			startActivityForResult(AddReceptAddressActivity.class, CODE_BACK_FROM_ADD);
			break;
		}
	}

	@Override
	public void init() {
		((TextView) findViewById(R.id.title_text)).setText("管理收货地址");
		findViewById(R.id.left_button).setOnClickListener(this);
		findViewById(R.id.btn_add).setOnClickListener(this);
		
		listView = (ListView) findViewById(R.id.listView);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
	}

	@Override
	public void initData() {
		try{
			UserInfo info = new UserInfo(this);
			JSONObject jo = new JSONObject();
			jo.put("userId", info.getUid());
			Bundle bundle = new Bundle();
			bundle.putString("request", Utils.requestParamsEncode(jo));
			HTTPRequest.POST(this, Config.REQUEST_URLS.URL_USER_ADDRESS_LIST, bundle, new onRequestOverListener() {
				@Override
				public void onRequestOver(String result) {
					try{
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("code") != 0){
							showToast(jo.getString("message"));
							return;
						}
						listView.setAdapter(new Adapter(jo.getJSONArray("response")));
					}catch(JSONException e){
						e.printStackTrace();
					}
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onNetworkChanged(boolean isMobNetConnected,
			boolean isWifiConnected) {
		// TODO Auto-generated method stub

	}

	private class Adapter extends BaseAdapter{

		private JSONArray ja = null;
		
		public Adapter(JSONArray ja) {
			this.ja = ja;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ja.length();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			try {
				return ja.getJSONObject(position).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

		public String getAddressId(int position){
			try {
				return ja.getJSONObject(position).getString("addressId");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = LayoutInflater.from(mContext).inflate(R.layout.item_receipt_address, null);
			}
			try{
				JSONObject jo = ja.getJSONObject(position);
				if(jo.getBoolean("iscommon")){
					convertView.findViewById(R.id.ic_gou).setVisibility(View.VISIBLE);
					convertView.setBackgroundColor(0xff737373);
				}else{
					convertView.findViewById(R.id.ic_gou).setVisibility(View.INVISIBLE);
					convertView.setBackgroundColor(0xff323232);
				}
				TextView tv_address = (TextView) convertView.findViewById(R.id.tv_address);
				TextView tv_mobile = (TextView) convertView.findViewById(R.id.tv_mobile);
				TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
				convertView.setTag(jo.getString("addressId"));
				tv_name.setText(jo.getString("name"));
				tv_mobile.setText(jo.getString("phone"));
				tv_address.setText(jo.getString("address"));
			}catch(JSONException e){
				e.printStackTrace();
			}
			return convertView;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == CODE_BACK_FROM_ADD && resultCode == RESULT_OK){
			initData();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		boolean isSelect = getIntent().getBooleanExtra("isSelect", false);
		if(isSelect){
			Intent i = new Intent();
			i.putExtra("addressData", (String)(listView.getAdapter().getItem(position)));
			setResult(RESULT_OK, i);
			finish();
			return;
		}
		Intent i = new Intent(this,AddReceptAddressActivity.class);
		i.putExtra("data", (String)(listView.getAdapter().getItem(position)));
		startActivityForResult(i, CODE_BACK_FROM_ADD);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position,
			long arg3) {
		Dialog.showMessageDialog(this, "提示", "进行什么操作？", "设为常用地址", "删除地址", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String address_id = ((Adapter)listView.getAdapter()).getAddressId(position);
				try{
					JSONObject jo = new JSONObject();
					jo.put("userId", Config.getUserId(mContext));
					jo.put("addressId", address_id);
					Bundle bundle = new Bundle();
					bundle.putString("request", Utils.requestParamsEncode(jo));
					String url = Config.REQUEST_URLS.URL_USER_DELETE_ADDRESS_INFO;
					if(which == DialogInterface.BUTTON_POSITIVE){
						url = Config.REQUEST_URLS.URL_USER_SET_ADDRESS_COMMON;
					}
					HTTPRequest.POST(mContext, url, bundle, new onRequestOverListener() {
						@Override
						public void onRequestOver(String result) {
							try{
								JSONObject jo = new JSONObject(result);
								showToast(jo.getString("message"));
								if(jo.getInt("code") != 0){
									return;
								}
								initData();
							}catch(JSONException e){
								e.printStackTrace();
							}
						}
					});
				}catch(Exception e){
					
				}
			}
		});
		return true;
	}
	
	
}
